<?php

use Illuminate\Database\Capsule\Manager as DB;
use app\modules\Merchant\models\goodsModel;
use app\modules\Merchant\models\categoryModel;

class Dianpu_IndexController extends CommonController
{
    protected $authExcept = ['lists', 'detail', 'goodslist', 'goodsdetail', 'commentlist', 'template'];

    public function listsAction()
    {
        $params = $this->get();
        $query = dianpuModel::with(['member']);

        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;
        $offset = ($page - 1) * $per_page;
        $total = $query->count();
        $rows = $query->orderBy('id', 'desc')->offset($offset)->limit($per_page)->get();
        foreach ($rows as $row) {
            $item = [
                'id' => $row->id,
                'name' => $row->name,
            ];
            foreach ($row->member as $member) {
                $item['member'] = $member;
                break;
            }
            $item['goods'] = goodsModel::where('status', 'up')
                ->where('dianpu_id', $row->id)
                ->where('image', 'like', 'http%')
                ->limit(3)
                ->get();
            $list[] = $item;
        }

        $data = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $list ?? [],
        ];
        json(['code' => 1, 'msg' => '店铺列表', 'data' => $data]);
    }

    public function detailAction()
    {
        $id = $this->get('id');
        $row = dianpuModel::with(['member', 'banner'])->find($id);
        $data = [
            'id' => $id,
            'name' => $row->name,
            'company_name' => $row->company_name,
            'phone' => $row->phone,
            'address' => $row->address,
            'banner' => [],
        ];
        $banner = $row->banner;
        foreach ($banner as $bitem) {
            $data['banner'][] = ['image' => $bitem->image];
        }
        foreach ($row->member as $member) {
            $data['member'] = $member;
            break;
        }
        json(['code' => 1, 'msg' => '商品详情', 'data' => $data]);
    }

    public function realtimeinfoAction()
    {
        $dianpu_id = $this->get('dianpu_id') ?: 0;
        $query = DB::select(
            'SELECT COUNT(DISTINCT a.member_id) cnt FROM cs_member_view a INNER JOIN cs_goods b ON a.goods_id=b.id INNER JOIN cs_dianpu c ON b.dianpu_id=c.id WHERE c.id=? and a.created_at>?',
            [$dianpu_id, date('Y-m-d')]
        );
        $today_visit = $query[0];
        $query = DB::select(
            "SELECT COUNT(*) pay_count,SUM(b.pay_fee) pay_amount FROM cs_order_action a INNER JOIN cs_order b ON a.order_id=b.id WHERE a.`remark`='用户支付成功' AND b.dianpu_id=? and a.created_at>?",
            [$dianpu_id, date('Y-m-d')]
        );
        $today_order = $query[0];
        $total_amount = orderModel::where('dianpu_id', $dianpu_id)->where('status', '>', 0)->sum('pay_fee');
        $all_reward_amount = 0;
        $balance_amount = bcsub($total_amount, $all_reward_amount, 2);
        $data = [
            'today_visit_count' => $today_visit->cnt ?? 0,
            'today_pay_count' => $today_order->pay_count ?? 0,
            'today_pay_amount' => $today_order->pay_amount ?? 0,
            'total_amount' => $total_amount,
            'balance_amount' => $balance_amount,
        ];
        json(['code' => 1, 'msg' => '', 'data' => $data]);
    }

    public function goodslistAction()
    {
        $dianpu_id = $this->get('dianpu_id');
        $category = DB::table('category')
            ->where('status', 'normal')
            ->where('dianpu_id', $dianpu_id)
            ->select('id', 'name', DB::raw("0 as goodsCount"))
            ->get();

        $categoryList = [];
        $goodsList = [];

        $goods = goodsModel::where('status', 'up')
            ->where('dianpu_id', $dianpu_id)
            ->select('id', 'category_ids', 'title', 'subtitle', 'is_sku', 'price', 'original_price', 'image')
            ->limit(100)
            ->get();
        foreach ($goods as $goods_item) {
            $all_goods_ids[] = $goods_item->id;
            $goods_item_category_ids = explode(',', $goods_item->category_ids);
            foreach ($category as $category_item) {
                if (in_array($category_item->id, $goods_item_category_ids)) {
                    $category_item->goodsCount += 1;
                    $goodsList[] = [
                        'id' => $goods_item->id,
                        'category_id' => $category_item->id,
                        'title' => $goods_item->title,
                        'subtitle' => $goods_item->subtitle,
                        'is_sku' => $goods_item->is_sku,
                        'price' => $goods_item->price,
                        'original_price' => $goods_item->original_price,
                        'image' => $goods_item->image,
                    ];
                    break;
                }
            }
        }
        foreach ($category as $category_item) {
            if ($category_item->goodsCount > 0) {
                $category_item->number = 0;
                unset($category_item->goodsCount);
                $categoryList[] = $category_item;
            }
        }
        $sku_price = goodsskupriceModel::query()
            ->whereIn('goods_id', $all_goods_ids ?? [])
            ->where('status', 'up')
            ->where('stock', '>', 0)
            ->select('id', 'goods_id', 'goods_sku_ids', 'price', 'image', 'stock', 'goods_sku_text')
            ->orderBy('weight', 'DESC')
            ->get();
        $all_sku_ids = [];
        foreach ($sku_price as $sku_price_item) {
            $sku_price_item_skuids = $sku_price_item->goods_sku_ids ? explode(',', $sku_price_item->goods_sku_ids) : [];
            $all_sku_ids = array_unique(array_merge($all_sku_ids, $sku_price_item_skuids));
        }
        $sku = goodsskuModel::whereIn('id', $all_sku_ids ?? [])->select(['id', 'pid', 'name'])->get();
        foreach ($sku as $sku_item) {
            $top_sku_ids[] = $sku_item->pid;
        }
        $top_sku = goodsskuModel::whereIn('id', $top_sku_ids ?? [])->select(['id', 'name'])->get();

        foreach ($goodsList as $goodsKey => $goodsItem) {
            $goods_sku = [];
            $goods_sku_price = [];
            $goods_sku_ids = [];
            foreach ($sku_price as $sku_price_item) {
                if ($sku_price_item->goods_id == $goodsItem['id']) {
                    $sku_ids_tmp = explode(',', $sku_price_item->goods_sku_ids);
                    $sku_price_temp = [
                        'id' => $sku_price_item->id,
                        'goods_id' => $sku_price_item->goods_id,
                        'goods_sku_id_arr' => array_map('intval', $sku_ids_tmp),
                        'price' => $sku_price_item->price,
                        'image' => $sku_price_item->image,
                        'stock' => $sku_price_item->stock,
                        'goods_sku_text' => $sku_price_item->getRawOriginal('goods_sku_text'),
                    ];
                    $goods_sku_ids = array_unique(array_merge($goods_sku_ids, $sku_price_temp['goods_sku_id_arr']));
                    $goods_sku_price[] = $sku_price_temp;
                }
            }
            $goodsList[$goodsKey]['sku_price'] = $goods_sku_price;

            $goods_top_sku_ids = [];
            foreach ($goods_sku_ids as $goods_sku_id) {
                foreach ($sku as $sku_item) {
                    if ($goods_sku_id == $sku_item->id) {
                        $goods_sku[] = $sku_item;
                        break;
                    }
                }
            }
            foreach ($goods_sku as $goods_sku_item) {
                if (array_search($goods_sku_item->pid, $goods_top_sku_ids) === false) {
                    $goods_top_sku_ids[] = $goods_sku_item->pid;
                }
            }
            $goods_sku_tmp = [];
            foreach ($goods_top_sku_ids as $goods_top_sku_id) {
                $goods_sku_tmp_item = null;
                foreach ($top_sku as $top_sku_item) {
                    if ($top_sku_item->id == $goods_top_sku_id) {
                        $goods_sku_tmp_item = $top_sku_item;
                        break;
                    }
                }
                if ($goods_sku_tmp_item) {
                    $goods_sku_tmp_item_children = [];
                    foreach ($goods_sku as $goods_sku_item) {
                        if ($goods_sku_item->pid == $goods_top_sku_id) {
                            $goods_sku_tmp_item_children[] = $goods_sku_item;
                        }
                    }
                    $goods_sku_tmp_item->content = $goods_sku_tmp_item_children;
                }
                $goods_sku_tmp[] = $goods_sku_tmp_item;
            }
            $goodsList[$goodsKey]['sku'] = $goods_sku_tmp;
        }

        json(['code' => 1, 'msg' => '店铺商品', 'data' => ['categoryList' => $categoryList, 'goodsList' => $goodsList]]);
    }

    public function goodsAction()
    {
        $dianpu_id = $this->get('dianpu_id');
        $type = $this->get('type') ?: 'up';
        $order = $this->get('order') ?: 'created_at';
        $order = ($order == 'stock') ? 'b.stock' : 'a.' . $order;
        $sort = $this->get('sort') ?: 'asc';
        $sort = (strtolower($sort) == 'asc') ? 'ASC' : 'DESC';
        $goodsList = DB::select(
            "SELECT a.`id`,a.`title`,a.sales,a.price,a.image,a.`status`,a.created_at,b.stock FROM cs_goods a INNER JOIN (SELECT goods_id, SUM(stock) AS stock FROM cs_goods_sku_price GROUP BY goods_id) b ON a.id=b.goods_id WHERE a.dianpu_id=? AND a.`status`=? ORDER BY {$order} {$sort}",
            [$dianpu_id, $type]
        );
        json(['code' => 1, 'data' => $goodsList]);
    }

    public function goodsupdownAction()
    {
        $user = \app\service\auth::userinfo();
        $dianpu_id = $user['dianpu']['id'] ?? 0;
        $goods_id = $this->get('goods_id');
        $goods = goodsModel::where('dianpu_id', $dianpu_id)->find($goods_id);
        if (!$dianpu_id || !$goods) {
            json(['code' => 0, 'msg' => '店铺商品不存在']);
            exit;
        }
        $type = strtolower($this->get('type'));
        if (!in_array($type, ['up', 'down'])) {
            json(['code' => 0, 'msg' => '参数不合法']);
            exit;
        }
        goodsModel::where('id', $goods_id)->update(['status' => $type]);
        json(['code' => 1, 'data' => '操作成功']);
    }

    public function goodsdetailAction()
    {
        $id = $this->get('id');
        $goods = goodsModel::where('status', 'up')
            ->select(['id', 'dianpu_id', 'category_ids', 'title', 'subtitle', 'is_sku', 'price', 'original_price', 'image', 'images', 'content'])
            ->find($id);

        if (!$goods) {
            json(['code' => 0]);
            exit;
        }

        $goods->dianpu_id = 4;
        if (substr($goods->image, 0, 4) != 'http') {
            $goods->image = 'http://stjk.zmssp.cn' . $goods->image;
        }
        $imgs = array_filter(explode(',', $goods->getRawOriginal('images')));
        foreach ($imgs as $image_key => $image_item) {
            if (substr($image_item, 0, 4) != 'http') {
                $imgs[$image_key] = 'http://stjk.zmssp.cn' . $image_item;
            }
        }
        $goods->imgs = $imgs;
        unset($goods->images);

        $sku_price = goodsskupriceModel::where('goods_id', $id)
            ->where('status', 'up')
            ->where('stock', '>', 0)
            ->select(['id', 'goods_id', 'goods_sku_ids', 'price', 'image', 'stock', 'goods_sku_text'])
            ->orderBy('weight')
            ->get();
        $all_sku_ids = [];
        foreach ($sku_price as $sku_price_item) {
            $sku_price_item_skuids = $sku_price_item->goods_sku_ids ? explode(',', $sku_price_item->goods_sku_ids) : [];
            $all_sku_ids = array_unique(array_merge($all_sku_ids, $sku_price_item_skuids));
        }
        $sku = goodsskuModel::whereIn('id', $all_sku_ids ?? [])->select(['id', 'pid', 'name'])->get();
        foreach ($sku as $sku_item) {
            $top_sku_ids[] = $sku_item->pid;
        }
        $top_sku = goodsskuModel::whereIn('id', $top_sku_ids ?? [])->select(['id', 'name'])->get();

        $goods_sku = [];
        $goods_sku_price = [];
        $goods_sku_ids = [];

        foreach ($sku_price as $sku_price_item) {
            if ($sku_price_item->goods_id == $goods->id) {
                $sku_ids_tmp = explode(',', $sku_price_item->goods_sku_ids);
                $sku_price_temp = [
                    'id' => $sku_price_item->id,
                    'goods_id' => $sku_price_item->goods_id,
                    'goods_sku_id_arr' => array_map('intval', $sku_ids_tmp),
                    'price' => $sku_price_item->price,
                    'image' => $sku_price_item->image,
                    'stock' => $sku_price_item->stock,
                    'goods_sku_text' => $sku_price_item->getRawOriginal('goods_sku_text'),
                ];
                $goods_sku_ids = array_unique(array_merge($goods_sku_ids, $sku_price_temp['goods_sku_id_arr']));
                $goods_sku_price[] = $sku_price_temp;
            }
        }
        $goods->sku_price = $goods_sku_price;

        $goods_top_sku_ids = [];
        foreach ($goods_sku_ids as $goods_sku_id) {
            foreach ($sku as $sku_item) {
                if ($goods_sku_id == $sku_item->id) {
                    $goods_sku[] = $sku_item;
                    break;
                }
            }
        }
        foreach ($goods_sku as $goods_sku_item) {
            if (array_search($goods_sku_item->pid, $goods_top_sku_ids) === false) {
                $goods_top_sku_ids[] = $goods_sku_item->pid;
            }
        }
        $goods_sku_tmp = [];
        foreach ($goods_top_sku_ids as $goods_top_sku_id) {
            $goods_sku_tmp_item = null;
            foreach ($top_sku as $top_sku_item) {
                if ($top_sku_item->id == $goods_top_sku_id) {
                    $goods_sku_tmp_item = $top_sku_item;
                    break;
                }
            }
            if ($goods_sku_tmp_item) {
                $goods_sku_tmp_item_children = [];
                foreach ($goods_sku as $goods_sku_item) {
                    if ($goods_sku_item->pid == $goods_top_sku_id) {
                        $goods_sku_tmp_item_children[] = $goods_sku_item;
                    }
                }
                $goods_sku_tmp_item->content = $goods_sku_tmp_item_children;
            }
            $goods_sku_tmp[] = $goods_sku_tmp_item;
        }
        $goods->sku = $goods_sku_tmp;

        json(['code' => 1, 'msg' => '店铺商品详情', 'data' => $goods]);
    }

    public function commentlistAction()
    {
        $dianpu_id = $this->get('dianpu_id');
        json(['code' => 1, 'msg' => '店铺评论', 'data' => []]);
    }

    public function submitorderAction()
    {
        $goods_list = $this->get('goods_list');
        $address_id = $this->get('address_id');
        if (empty($goods_list)) {
            json(['code' => 0, 'msg' => '订单商品有误']);
            exit;
        }
        if (empty($address_id)) {
            json(['code' => 0, 'msg' => '收货地址有误']);
            exit;
        }
        array_walk($goods_list, function (&$item) {
            $item = [
                'goods_id' => $item['goods_id'],
                'sku_price_id' => $item['goods_sku_price_id'],
                'number' => $item['number'],
            ];
        });
        $params = [
            'from' => 'dianpu',
            'order_type' => 'goods',
            'groupon_id' => 0,
            'buy_type' => 'alone',
            'goods_list' => $goods_list,
            'address_id' => $address_id,
            'coupons_id' => 0,
            'activity_id' => 0,
            'dianpu_id' => goodsModel::where('id', $goods_list[0]['goods_id'])->value('dianpu_id'),
        ];
        if ($this->get('debug')) {
            json(['code' => 0, 'msg' => '调试参数', 'data' => $params]);
            exit;
        }
//        $params['preorder'] = orderModel::previewOrder($params);

        if ($this->get('debugpre')) {
            json(['code' => 0, 'msg' => '订单预览', 'data' => $params]);
            exit;
        }
        $data = orderModel::createOrder($params);
        if (!$data) {
            json(['code' => 0, 'msg' => '订单提交失败', 'data' => $params]);
            exit;
        }

        json(['code' => 1, 'msg' => '订单添加成功', 'data' => $data]);
    }

    // 商城模板数据
    public function templateAction()
    {
        $get = $this->get();
        $platform = getallheaders()['Platform'];
        if (isset($get['dianpu_id']) && $get['dianpu_id'] != 0) {
            $template = decorateModel::getCurrentPlatformDecorate('preview', $get['dianpu_id']);
        } else {
            $template = decorateModel::getCurrentPlatformDecorate($platform);
        }
        json(['code' => 1, 'msg' => '店铺模板数据', 'data' => $template]);
    }

}
